package com.lhy.gulimall.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhy.common.utils.PageUtils;
import com.lhy.common.utils.Query;
import com.lhy.gulimall.product.dao.CategoryDao;
import com.lhy.gulimall.product.entity.CategoryEntity;
import com.lhy.gulimall.product.service.CategoryBrandRelationService;
import com.lhy.gulimall.product.service.CategoryService;
import com.lhy.gulimall.product.vo.Catelog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    private CategoryEntity categoryEntity = new CategoryEntity();
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //找到所有一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu,categoryEntities));
                    return menu;
                })
                .sorted((menu1,menu2) ->{
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 1、检查当前删除的菜单，是否被其他的地方引用
        // 逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 递归查找所有菜单的子菜单
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();

        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);

        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有的数据
     * @param category
     */
    @Override
    @CacheEvict(value = {"category"}, key="'getLevel1Catagorys'")
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }

    @Cacheable(value = {"category"}, key="'getLevel1Catagorys'")
    @Override
    public List<CategoryEntity> getLevel1Catagorys() {
        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }


    // TODO 产生对外内存溢出： OutOfDirectMemoryError
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        log.info("线程-》{}---{}",Thread.currentThread().getName(),categoryEntity.hashCode());
        // 加入缓存逻辑
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        // 缓存中没有就查数据库
        if (StringUtils.isEmpty(catalogJSON)) {
            log.info("缓存未命中，将要查询数据库");
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();

            return catalogJsonFromDb;
        }
        log.info("命中缓存，直接返回");
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>(){});

        return result;
    }

    /**
     * 缓存中的数据和数据库数据库的一致性
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        RLock lock = redissonClient.getLock("redisson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDb = null;
        try{
            dataFromDb = getDataFromDb();
        } catch (Exception e) {

        }finally {
            lock.unlock();
        }
        return dataFromDb;
    }
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {
        String token = UUID.randomUUID().toString();
        // 1、占用分布式锁，设置过期时间
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", token,300,TimeUnit.SECONDS);
        //加锁成功
        if (lock) {
            log.info("获取分布式锁成功");
            Map<String, List<Catelog2Vo>> dataFromDb;
            try{
                dataFromDb = getDataFromDb();
            }finally {
                String lockValue = redisTemplate.opsForValue().get("lock");
//            if (StringUtils.equals(lockValue, token)) {
//                // 删除锁
//                redisTemplate.delete("lock");
//            }
                //原子操作
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                //删除锁
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), token);
                log.info("lock1--->{}",lock1);
            }
            return dataFromDb;
        }
        log.info("获取分布式锁失败。。。等待重试");
        //加锁失败，重试
        // 休眠 100ms 再重试
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return getCatalogJsonFromDbWithRedisLock();
    }

    /**
     * 从数据库获取
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {

        /*
        将数据库查询变为一次查询
         */
        synchronized (this){
            return getDataFromDb();
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        // 缓存中没有就查数据库
        if (StringUtils.isNotEmpty(catalogJSON)) {
            return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        }

        log.info("查询数据库->{}", Thread.currentThread().getName());
        List<CategoryEntity> selectList = baseMapper.selectList(new QueryWrapper<CategoryEntity>());

        // 1、查出所有的1级分类
//        List<CategoryEntity> level1Catagorys = getLevel1Catagorys();
        List<CategoryEntity> level1Catagorys = getParentCid(selectList,0l);

        //2、 封装数据
        Map<String, List<Catelog2Vo>> map = level1Catagorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParentCid(selectList,v.getCatId());

            // 封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (CollUtil.isNotEmpty(categoryEntities)) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> categoryEntityList = getParentCid(selectList,l2.getCatId());
                    if (CollUtil.isNotEmpty(categoryEntityList)) {
                        List<Catelog2Vo.Catelog3Vo> collect2 = categoryEntityList.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect2);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));

        catalogJSON = JSON.toJSONString(map);
        // 查到的结果放入redis中
        redisTemplate.opsForValue().set("catalogJSON", catalogJSON);
        return map;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList,long parentCid) {
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        return selectList.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths) {
        // 收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

}